package me.hl.nio;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Created by Planck on 2016/2/19.
 */
public class BufferDemo {
    private Logger logger = LoggerFactory.getLogger(BufferDemo.class);

    @Test
    public void readBufferDemo() throws Exception {
        RandomAccessFile file = new RandomAccessFile("E://test.txt", "rw");
        FileChannel fileChannel = file.getChannel();
        ByteBuffer buf = ByteBuffer.allocate(48);
        int read = fileChannel.read(buf);//从Channel写到Buffer
        while (read != -1) {
            buf.flip();//反转buf模式,将buf的模式从写变成读

            while (buf.hasRemaining()) {
                System.out.print((char) buf.get());
            }
            // buf.clear();//clear()方法会清空整个缓冲区
            buf.compact();//compact()方法只会清除已经读过的数据
            read = fileChannel.read(buf);
        }
    }

    @Test
    public void writeBufferDemo() throws Exception {
        RandomAccessFile file = new RandomAccessFile("E://test.txt", "rw");

        FileChannel fileChannel = file.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        byteBuffer.put("1207".getBytes());
        byteBuffer.flip();
        fileChannel.write(byteBuffer, file.length());//记得要加长度。不然会被覆盖的
    }

    @Test
    public void gatheringDemo() throws Exception {
        RandomAccessFile file = new RandomAccessFile("E://test.txt", "rw");
        FileChannel channel = file.getChannel();
        ByteBuffer buf1 = ByteBuffer.allocate(1024);
        ByteBuffer buf2 = ByteBuffer.allocate(1024);
        buf1.put("1994".getBytes());
        buf1.flip();
        buf2.put("1207".getBytes());
        buf2.flip();
        ByteBuffer[] bufs = {buf1, buf2};
        channel.write(bufs);

    }


    @Test
    public void scatteringDemo() throws Exception {
        RandomAccessFile file = new RandomAccessFile("E://test.txt", "rw");
        FileChannel channel = file.getChannel();
        ByteBuffer buffer1 = ByteBuffer.allocate(4);
        ByteBuffer buffer2 = ByteBuffer.allocate(4);
        ByteBuffer[] bufs = {buffer1, buffer2};
        channel.read(bufs);
        buffer1.flip();
        buffer2.flip();
        while (buffer1.hasRemaining()) {
            logger.info("{}", (char) buffer1.get());
        }
        while (buffer2.hasRemaining()) {
            logger.info("{}", (char) buffer2.get());
        }

    }


}
